function DecodingProbability()

% Finite precision sensitive :/

clear all
close all
clc

% Working example!
    % n1=12;
    % k1=10;
    % r=k1;
    % q=2;
    % dm=DifferentMatrices(n1,k1,q)
    % test_val=MatricesWithRank(n1,k1,r,q)/dm
    % % 1-test_val

%% Quick testing!

% Transmitting layer 1
k1=10;
q=2;
r=k1;
p_decode_l1=zeros(30,1);
p_decode_l1(1:k1-1)=NaN;
for g=k1:30
    dm=DifferentMatrices(g,k1,q);
    p_decode_l1(g)=MatricesWithRank(g,k1,r,q)/dm;
end

% Quick plotting
figure(1)
hold('on')
plot(1:30,p_decode_l1,'-*')
hold('off')

grid('on')
pbaspect([2.5 1 1])
set(gca,'XTick',0:2:3000)
xlim([0 50])
ylim([0 1])

% Save plot
print(gcf,'uep_ew_analytic.eps')


end


% Should work
function MWR = MatricesWithRank(m,n,r,q)

% Get first set of gaussian coefficients
gc=gausscoeffs(n,r,q)

% Calculate "sum"
val=0;
for k=0:r
    
    % This should be the one!
    val=val+((-1)^(r-k)*gausscoeffs(r,k,q)*q^(m*k+binomcoeffs(r-k,2)));
end

% Return total number of matrices 'm'x'n' with rank 'r'
val

MWR=gc*val

end

% Should work (No need to test)
function DM = DifferentMatrices(m,n,q)
DM=q^(m*n);
end

% Should work (Tested! see bottom)
function GC = gausscoeffs(m,r,q)
if r==0
    %     disp('r = 0 in gauss coeffs')
    GC=1;
elseif r>0
    %     disp('r > 0 in gauss coeffs')
    
    % Calculate numerator
    num=1;
    for w=m:-1:m-r+1
        num=num*(q^w-1);
    end
    
    % Calculate denominator
    denom=1;
    for w=r:-1:1
        denom=denom*(q^w-1);
    end
    
    % Calculate gaussian coefficient
    GC=num/denom;
    
elseif r<0
    disp('r < 0 error in gausscoeffs!!')
end


end

% Should work (Not tested)
% Is not precision critical
function bc = binomcoeffs(n,k)
% As on page 123 in "A course in combinatorics"

num=n;
for w=-1:-1:-k+1
    num=num*(num+w);
end

denom=factorial(k);
bc=num/denom;

end





%%  junk!!!

%val=val+((-1)^(r-k)*gausscoeffs(r,k,q)*q^(n*k+nchoosek(r-k,2)));
% NOTE: We must not take nchoosek(0,2)!
% Are we making a mistake? The book says we should?
% Is this right?
% val=val+((-1)^(r-k)*gausscoeffs(r,k,q)*q^(n*k+nchoosek(r-k,2)));

% Testing Gaussian Coefficient generater

% Correct values are from: http://mathworld.wolfram.com/q-BinomialCoefficient.html
%
% m=2;
% r=1;
% q=2;
%
% if gausscoeffs(m,r,q) == (1+q)
%     disp('gauss test 1 succes!')
% end
%
% m=3;
% r=1;
% q=2;
%
% if gausscoeffs(m,r,q) == (1+q+q^2)
%     disp('gauss test 2 succes!')
% end




